<template>
  <div
    v-loading="loading"
    ref="chartsRef"
    style="width: 100%; height: 230px"
  ></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'
import useFetch from '@/hooks/useFetch'
import { listAllDeptCardNum } from '@/api/home'
import { cloneDeep } from 'lodash-es'

const chartsRef = ref<HTMLDivElement>(null)
const defaultFillArr = new Array(20).fill(0)
const defaultSeries = [
  {
    data: defaultFillArr,
    type: 'bar',
    barWidth: 26,
    stack: 'a',
    name: '黄牌数量',
    itemStyle: {
      color: '#E37318',
    },
  },
  {
    data: defaultFillArr,
    type: 'bar',
    barWidth: 26,
    stack: 'a',
    name: '红牌数量',
    itemStyle: {
      color: '#D54941',
    },
  },
]

const defaultFillData = new Array(20).fill('')

const { loading, execute, onFetchSuccess } = useFetch(listAllDeptCardNum)

onFetchSuccess((data) => {
  const lastData = data?.data ?? []
  if (lastData?.length) {
    const axisData = lastData.map((item) => item?.unitForShort ?? '')
    const redCardNum = lastData.map((item) => item?.redCardNum ?? 0)
    const yellowCardNum = lastData.map((item) => item?.yellowCardNum ?? 0)

    const newSeries = cloneDeep(defaultSeries)
    options.value.xAxis.data = axisData
    newSeries[0].data = yellowCardNum
    newSeries[1].data = redCardNum
    options.value.series = newSeries
  }
  initCharts()
})

const options = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    show: true,
  },
  grid: {
    top: '15%',
    left: '5%',
    right: 0,
    bottom: '30%',
  },
  xAxis: {
    type: 'category',
    data: defaultFillData,
    axisLabel: {
      rotate: 30,
      interval: 0,
      color: '#6F7686',
    },
  },
  yAxis: [
    {
      type: 'value',
      name: '发牌数(张)',
    },
    {
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: '#999',
      },
    },
  ],
  dataZoom: [
    {
      type: 'inside',
    },
  ],
  series: defaultSeries,
})

const charts = ref(null)

onMounted(() => {
  init()
})

const init = async () => {
  await execute({
    currentPage: 1,
    pageSize: 20,
  })
}

const initCharts = () => {
  if (chartsRef?.value) {
    const chart = echarts.init(chartsRef.value)
    chart.setOption(options.value)
    charts.value = chart
    // 窗口变化自适应
    window.addEventListener('resize', handleResize)
  }
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  charts.value?.resize()
}
</script>
